package com.hy.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.hy.parse.DomParser;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

/**
 * 文件处理类
 * @author hy
 * @since 2016-11-09
 */
public class FileHelper {
	
	private static final String SEPARATOR = "/";
	
	private static final String GENERATOR_OUTPUT = "generator-output";

	/** 模板路径 */
	private static final String SUB_VM_DIRECTORY = "com/hy/vm";
	
	/**
	 * 递归生成文件
	 * @param directory
	 * @param mapXml
	 * @throws IOException
	 */
	public static void fileTree(String directory, Map<String, Object> mapXml) throws IOException {
		
		// 创建引擎  
        VelocityEngine ve = new VelocityEngine();
        // 设置模板加载路径，这里设置的是class下  
        ve.setProperty(Velocity.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        // 进行初始化操作
        ve.init();
        // 设置初始化数据
        VelocityContext context = new VelocityContext();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
        String SYSTEM_CURRENT_TIME = sdf.format(new Date());
        context.put("SYSTEM_CURRENT_TIME", SYSTEM_CURRENT_TIME);
        for(Map.Entry<String, Object> entry : mapXml.entrySet()){
        	context.put(entry.getKey(), entry.getValue());
        }
        //outRoot
        String outRoot = mapXml.containsKey("outRoot") ? mapXml.get("outRoot").toString() : GENERATOR_OUTPUT;
        //basepackage
        String basepackageTmp = mapXml.get("basepackage").toString();
		//要生成的文件夹路径
		String basepackage = basepackageTmp.replace(".", "/");
		File basepackageFile = new File(outRoot + SEPARATOR + basepackage);
		if(!basepackageFile.exists()){
			basepackageFile.mkdirs();
		}
        
		File file = new File(ClassUtils.getClassPath() + SEPARATOR + directory);
		String []vmFiles = file.list();
		if(vmFiles != null && vmFiles.length > 0){
			for(String vmFileStr : vmFiles){
				// directory="com/hy/vm"
				String vmFileDir = ClassUtils.getClassPath() + directory + SEPARATOR + vmFileStr;
				File vmFile = new File(vmFileDir);
				//outRoot/${basepackage}
				String newFileDirTmp = (outRoot + SEPARATOR + directory + SEPARATOR + vmFileStr).replace(SUB_VM_DIRECTORY + SEPARATOR, "");
				String newFileDir = newFileDirTmp.replace("${basepackage}", basepackage);
				if(vmFile.isDirectory()){
					File newFile = new File(newFileDir);
					if(!newFile.exists()){
						newFile.mkdirs();
					}
					//递归生成文件
					fileTree(directory + SEPARATOR + vmFileStr, mapXml);
				}else if(vmFile.isFile()){
					String newFileURLTmp = newFileDir.replace("${className}", mapXml.get("className").toString());
					//生成文件路径
					String newFileURL = newFileURLTmp.substring(0, newFileURLTmp.lastIndexOf(".vm"));
//					System.out.println(newFileURL);
					
					//vm不包含src的路径
					String vmFileDirPath = directory + SEPARATOR + vmFileStr;
					// 加载模板，设定模板编码  
	                Template t = ve.getTemplate(vmFileDirPath, mapXml.get("encode").toString());
	                // 设置输出  
	                StringWriter writer = new StringWriter();
	                // 将环境数据转化输出
	                t.merge(context, writer);
	                System.out.println(writer.toString());
	                //
	                FileWriter fr = null;
	                fr = new FileWriter(newFileURL);
	                fr.write(writer.toString());
	                fr.flush();
	                fr.close();
				}
			}
		}
	}
	
	/**
	 * 输出文件
	 */
	public static void generateFile(){
    	//从xml模板读取数据
    	List<Map<String, Object>> xmlList = DomParser.parseXml();
    	for(Map<String, Object> mapXml : xmlList){
    		try {
				fileTree(SUB_VM_DIRECTORY, mapXml);
			} catch (IOException e) {
				e.printStackTrace();
			}
    	}
	}

}
